#!/usr/bin/python3
#coding:utf8

import serial
import argparse
import random
import time

def init_serial(dev):
    dev = '/dev/' + dev
    print(dev)
    ser = serial.Serial(dev, 9600)
    print(ser)
    if ser is not None:
        #ser.parity = 'N'
        #ser.stopbits = 1
        #ser.bytesize = 8
        # 30, 查询继电器状态
        ser.write(b'\x30')
        time.sleep(0.2)
        ret = ser.read()
        if len(ret)>0: return ser
    else:
        print("Fail to open dev: %s" % dev)
    return None

def test(action, status, n):
    cmd = '00'
    if action == 'ON':
        cmd += '01'
    elif action == 'OFF':
        cmd += '10'
    elif action == 'SET':
        cmd += '00'
    cmd += status

    cmd = '{:02x}'.format(int(cmd, 2))
    ser.write(bytes.fromhex(cmd))
    ret = ser.read()

    ret = int.from_bytes(ret, 'little')
    status = int(status, 2)
    print('test time: {}, action: {}, status: {:08b}, ret: {:08b}'.format(n, action, status, ret))

    if action == 'ON':
        assert(status == (status & ret))
    elif action == 'OFF':
        assert(status == (status & ~ret))
    elif action == 'SET':
        assert(status == ret)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--dev', default='ttyUSB0', help='input ttyUSB0')
    parser.add_argument('-n', '--num', type = int, help='input test times')
    args = parser.parse_args()

    actions = ['ON', 'OFF', 'SET']
    status = ['0000', '0001', '0010', '0011']

    ser = init_serial(args.dev)
    for n in range(args.num):
        test(actions[random.randrange(len(actions))], status[random.randrange(len(status))], n)
        #test(actions[1], status[random.randrange(len(status))])
        time.sleep(0.2)

